﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using BloggerAutoPosterService.Engine.Net;
using BloggerAutoPosterService.Engine.Utils;
using BloggerAutoPosterService.Engine.Models;
using BloggerAutoPosterService.Engine.WordPress;

namespace BloggerAutoPosterService.Engine.Core
{
    public class RunAll
    {
        #region Fields (3)

        readonly IList<IDataParser> _dataParsers;
        readonly IRedirectFinder _redirectFinder;
        readonly IServiceConfig _serviceConfig;

        #endregion Fields

        #region Constructors (1)

        public RunAll(IServiceConfig serviceConfig, IRedirectFinder redirectFinder)
        {
            _serviceConfig = serviceConfig;
            _redirectFinder = redirectFinder;
            _dataParsers = new List<IDataParser>
            {
                new ParseFeedAddToDB(_serviceConfig, _redirectFinder),
                new ParseGooglePlusAddToDb(_serviceConfig, _redirectFinder)
            };
        }

        #endregion Constructors

        #region Properties (1)

        private bool isBlogger
        {
            get { return _serviceConfig.BlogUrl.ToLowerInvariant().Contains("blogger.com"); }
        }

        #endregion Properties

        #region Methods (4)

        // Public Methods (3) 

        public void PostDataMarkAsSent()
        {
            var exportData = new ExportData(_serviceConfig);
            var dates = new List<string>
                            {
                                DateTime.Now.ToString("dd-MM-yyyy"),
                                DateTime.Now.AddDays(-1).ToString("dd-MM-yyyy")
                            };
            var todayList = exportData.DatesToList(dates);
            if (todayList == null || !todayList.Any()) return;

            var body = exportData.ListToString(todayList);
            if (string.IsNullOrEmpty(body)) return;

            var date = !_serviceConfig.UsePersianDate
                       ? DateTime.Now.ToString("dd-MM-yyyy")
                       : DateTime.Now.ToPersianDateTimeString();

            PostNews(body, date);
            writeToFile(body);
            new XmlDB(_serviceConfig).MarkAsSent(todayList);
        }

        public void PostNews(string body, string date)
        {
            if (!Downloader.IsConnectedToInternet) return;

            if (isBlogger)
            {
                new BloggerAutoPoster
                {
                    BlogUrl = _serviceConfig.BlogUrl,
                    UserName = _serviceConfig.UserName,
                    Password = _serviceConfig.Password,
                    PostAsDraft = false,
                    PostBody = body,
                    PostTags = new List<string>(_serviceConfig.Tag.ApplyUnifiedYeKe().Split(',')),
                    PostTitle = _serviceConfig.Title.ApplyUnifiedYeKe() + date
                }.PostNewEntry();
            }
            else
            {
                new MetaWeblogClient
                {
                    BlogUrl = _serviceConfig.BlogUrl,
                    UserName = _serviceConfig.UserName,
                    Password = _serviceConfig.Password,
                    PostAsDraft = false,
                    PostBody = body,
                    PostTags = new List<string>(_serviceConfig.Tag.ApplyUnifiedYeKe().Split(',')),
                    PostTitle = _serviceConfig.Title.ApplyUnifiedYeKe() + date
                }.PostNewEntry();
            }
        }

        public void ReadFeedSaveData(bool throwException = false, Action<NewsRecord> onNewsRecord = null)
        {
            if (!Downloader.IsConnectedToInternet) return;

            foreach (var parser in _dataParsers)
            {
                parser.OnNewsRecord = onNewsRecord;
                parser.SaveFeedData(throwException);
            }
        }
        // Private Methods (1) 

        private static void writeToFile(string body)
        {
            var dir = string.Format("{0}\\posts\\", Application.StartupPath);
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            File.WriteAllText(string.Format("{0}{1}.htm", dir, DateTime.Now.AddDays(-1).ToString("dd-MM-yyyy")), body);
        }

        #endregion Methods
    }
}
